package com.zkthink.ceres.sms.strategy.impl;

import com.alibaba.fastjson.JSONObject;
import com.zkthink.ceres.sms.enumeration.ProviderType;
import com.zkthink.ceres.sms.strategy.domain.SmsDO;
import com.zkthink.ceres.sms.strategy.domain.SmsResult;
import com.zkthink.ceres.sms.strategy.miaoxinclient.entity.MiaoxinResultItem;
import com.zkthink.ceres.sms.strategy.miaoxinclient.MiaoxinSmsClient;
import com.zkthink.ceres.sms.strategy.miaoxinclient.entity.MiaoxinResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 秒信云发送短信 实现类
 *
 * @Author: gzlv 2020/8/6 16:41
 */
@Component("MIAOXIN")
@Slf4j
public class SmsMiaoXinStrategy extends AbstractSmsStrategy {

    @Override
    protected SmsResult send(SmsDO smsDO) {
        try {
            MiaoxinSmsClient client = new MiaoxinSmsClient();
            //接受短信的手机号
            String mobile = smsDO.getPhone();
            //发送的内容
            Map<String,String> parse = (Map<String, String>) JSONObject.parse(smsDO.getTemplateParams());

            String format = MessageFormat.format(smsDO.getContent(), parse.values().toArray(new String[0]));
            String content = "【" + smsDO.getSignName() + "】" + format;

            client.setSecretkey(smsDO.getAppId(),smsDO.getAppSecret());
            String result = client.send(mobile, content, null, null);
            MiaoxinResult smsMiaoXinMsg = JSONObject.parseObject(result, MiaoxinResult.class);
            MiaoxinResultItem miaoxinResultItem = smsMiaoXinMsg.getResult().get(0);
            //TODO 发送结果不代表最终短信成功结果,如需查询短信发送结果请调用查询状态的接口,具体文档参考 http://docs.51miaoxin.com/sms/
            return SmsResult.build(ProviderType.MIAOXIN, String.valueOf(smsMiaoXinMsg.getCode()), miaoxinResultItem.getOrder_id(), null, miaoxinResultItem.getResult(), 0);
        } catch (IOException e) {
            e.printStackTrace();
            return SmsResult.fail(e.getMessage());
        }
    }
}
